package cn.easy.mortgage.web.app.mp;

import cn.easy.base.bean.PageBean;
import cn.easy.base.bean.common.AjaxResultBean;
import cn.easy.base.service.UserService;
import cn.easy.base.utils.BaseUtils;
import cn.easy.mobile.utils.ValidateUtil;
import cn.easy.mortgage.bean.HjPGSearchHouseBean;
import cn.easy.mortgage.bean.HjPGSearchHouseResultBean;
import cn.easy.mortgage.bean.HjPGSingleQueryBean;
import cn.easy.mortgage.bean.HjPGSingleQueryResultBean;
import cn.easy.mortgage.domain.Channel;
import cn.easy.mortgage.domain.EstateEvalInfo;
import cn.easy.mortgage.domain.LoanRequest;
import cn.easy.mortgage.service.*;
import cn.easy.mortgage.utils.Constants;
import cn.easy.mortgage.utils.ProjectUtil;
import cn.easy.mortgage.utils.SmsUtils;
import cn.easy.mortgage.utils.TokenUtils;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.utils.text.TextValidator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author huangm
 */
@Controller
@RequestMapping("/app/mp/mtg")
public class AppMpMtgController extends AppMpBaseController {
    @Autowired
    private EstateEvalInfoService estateEvalInfoService;
    @Autowired
    private HjPgService hjPgService;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private LoanRequestService loanRequestService;
    @Autowired
    private LvXinTongSmsService lvXinTongSmsService;
    @Autowired
    private UserService userService;

    @RequestMapping("")
    String index(Model model, HttpServletRequest request, PageBean pageBean) {
        String sessionId = request.getSession().getId();
        String token = TokenUtils.getToken(Constants.TOKEN_MD5_KEY, sessionId);
        model.addAttribute("token", token);
        ValidateUtil.checkExpire(TokenUtils.TOKEN_MAP, 1800);
        return "app/mp/mtg/index";
    }

    @RequestMapping(value = "/protocol", method = RequestMethod.GET)
    String protocol(HttpServletRequest request) {
        return "app/mp/mtg/protocol";
    }

    @RequestMapping(value = "/houseAddressPart", method = RequestMethod.GET)
    String houseAddressPart(@RequestParam(value = "regCode") String regCode,
                            @RequestParam(value = "propertyType") String propertyType,
                            @RequestParam(value = "addr") String addr,
                            Model model, HttpServletRequest request) {
        HjPGSearchHouseBean hjPGSearchHouseBean = new HjPGSearchHouseBean(addr, propertyType, regCode);
        HjPGSearchHouseResultBean hjPGSearchHouseResultBean = hjPgService.searchHouse(hjPGSearchHouseBean);
        model.addAttribute("searchHouseResultBean", hjPGSearchHouseResultBean);
        return "app/mp/mtg/houseAddressPart";
    }

    @RequestMapping(value = "/evalInfo", method = RequestMethod.GET)
    String evalInfo(@RequestParam(value = "id") String id, @RequestParam(value = "loanRequestId") String loanRequestId, Model model, HttpServletRequest request) {
        EstateEvalInfo estateEvalInfo = estateEvalInfoService.getOne(id);
        model.addAttribute("loanAmount", ProjectUtil.calLoanAmount(estateEvalInfo));
        model.addAttribute("estateEvalInfo", estateEvalInfo);
        model.addAttribute("loanRequestId", loanRequestId);

        return "app/mp/mtg/evalInfo";
    }

    @RequestMapping(value = "/loanRequest", method = RequestMethod.GET)
    String loanRequest(@RequestParam(value = "loanRequestId") String loanRequestId, Model model, HttpServletRequest request) {
        LoanRequest loanRequest = loanRequestService.getOne(loanRequestId);
        model.addAttribute("loanRequest", loanRequest);
        EstateEvalInfo estateEvalInfo = estateEvalInfoService.getOne(loanRequest.getEstateEvalId());
        model.addAttribute("loanAmount", ProjectUtil.calLoanAmount(estateEvalInfo));
        return "app/mp/mtg/loanRequest";
    }

    @RequestMapping(value = "/toEval", method = RequestMethod.POST)
    @ResponseBody
    AjaxResultBean toEval(HjPGSingleQueryBean hjPGSingleQueryBean, String mobile, String code, String regCode, Model model, HttpServletRequest request) {
        if (!BaseUtils.isDev() && !ValidateUtil.checkCode(SmsUtils.CODE_MAP, mobile, code, 900, true)) {
            return toError("验证码无效");
        }
        EstateEvalInfo estateEvalInfo = null;
        if (!estateEvalInfoService.evaluatedOnToday(hjPGSingleQueryBean.getHouseAddress(), hjPGSingleQueryBean.getRoomSize())) {
            HjPGSingleQueryResultBean hjPGSingleQueryResultBean = hjPgService.singleQuery(hjPGSingleQueryBean);
            if (hjPGSingleQueryResultBean == null || StringUtils.isBlank(hjPGSingleQueryResultBean.getFv_house_total_price())) {
                return toError("未查询到评估价格");
            }
            estateEvalInfo = estateEvalInfoService.valueOf(regCode, hjPGSingleQueryBean, hjPGSingleQueryResultBean);
            estateEvalInfo = estateEvalInfoService.save(estateEvalInfo);
        } else {
            estateEvalInfo = estateEvalInfoService.findByHouseAddressAndRoomSizeOnToday(hjPGSingleQueryBean.getHouseAddress(), hjPGSingleQueryBean.getRoomSize());
        }

        LoanRequest loanRequest = LoanRequest.valueOfH5(regCode, mobile, estateEvalInfo, getChannel(request));
        loanRequestService.save(loanRequest);
        Map<String, String> result = new HashMap<>();
        result.put("id", estateEvalInfo.getId());
        result.put("loanRequestId", loanRequest.getId());
        return toSuccess("查询成功", result);
    }

    @RequestMapping(value = "/toRequest", method = RequestMethod.POST)
    @ResponseBody
    AjaxResultBean toRequest(LoanRequest loanRequest, Model model, HttpServletRequest request) {
        if (!TextValidator.isMobileSimple(loanRequest.getMobile())) {
            return toError("手机号格式不正确");
        }
        loanRequest.setStatus(Constants.REQUEST_STATUS_SUBMIT);
        loanRequestService.save(loanRequest);
        return toSuccess("提交成功");
    }

    @RequestMapping(value = "/success", method = RequestMethod.GET)
    String success(LoanRequest loanRequest, Model model, HttpServletRequest request) {
        return "app/mp/mtg/success";
    }

    @RequestMapping(value = "/getCode", method = RequestMethod.POST)
    @ResponseBody
    AjaxResultBean getCode(String mobile, String key, HttpServletRequest request, HttpServletResponse response) {
        ValidateUtil.checkExpire(SmsUtils.CODE_MAP, 1800);
        String sessionId = request.getSession().getId();
        if (!TokenUtils.matchesToken(key, sessionId)) {
            return toError("访问无效");
        }
        if (!TextValidator.isMobileSimple(mobile)) {
            return toError("手机号格式不正确");
        }
        if (!ValidateUtil.validCodeSendInterval(SmsUtils.CODE_MAP, mobile, 60)) {
            return toError("验证码已发送，请60秒后重新获取");
        }
        if (!SmsUtils.checkSafe(mobile)) {
            return toError("发送频繁请稍后再试");
        }
        try {
            lvXinTongSmsService.sendCode(SmsUtils.CODE_MAP, mobile, getConfigStr(Constants.CODE_NOTICE_TEMPLATE_KEY));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return toSuccess("验证码已发送");
    }

    private String getChannelId(HttpServletRequest request) {
        Channel channel = getChannel(request);
        return channel == null ? null : channel.getId();
    }

    private Channel getChannel(HttpServletRequest request) {
        Object codeObj = request.getSession().getAttribute(Constants.CHANNEL_CODE);
        if (codeObj == null || StringUtils.isBlank(codeObj.toString())) {
            return null;
        }
        Channel channel = channelService.findByCode(codeObj.toString());
        return channel;
    }

}
